package com.platform.modules.sys.service.impl;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.platform.common.utils.*;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.enumstatus.AptitudeEnum;
import com.platform.common.enumstatus.SystemEnum;
import com.platform.common.enumstatus.UserEnum;
import com.platform.modules.mail.service.MailService;
import com.platform.modules.sys.dao.SysUserDao;
import com.platform.modules.sys.entity.SysOrgEntity;
import com.platform.modules.sys.entity.SysOrgUserEntity;
import com.platform.modules.sys.entity.SysRoleEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysDictService;
import com.platform.modules.sys.service.SysOrgService;
import com.platform.modules.sys.service.SysOrgUserService;
import com.platform.modules.sys.service.SysRoleService;
import com.platform.modules.sys.service.SysUserRoleService;
import com.platform.modules.sys.service.SysUserService;

/**
 * @author 肖亮
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysOrgUserService sysOrgUserService;
    @Autowired
    private MailService mailService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysOrgService sysOrgService;
    @Value("${spring.mail.emailTile}")
    private String emailTile;
    @Value("${spring.mail.emailParameter}")
    private String emailParameter;

    @Override
    public List<SysUserEntity> queryAll(Map<String, Object> params) {
        return baseMapper.selectUserList(params);
    }
    
    
    @Override
    public List<SysUserEntity> queryUserByOrgNo(Map<String, Object> params) {
        List<SysUserEntity> userList = baseMapper.selectListPage1(params);
        return userList;
    }

    /**
     * 查询人员信息（包括角色-人员所在单位）
     */
    @Override
    public Page<SysUserEntity> queryPage(Map<String, Object> params) {
        // 排序
        params.put("sidx", "T.CREATE_TIME");
        params.put("asc", false);
        Page<SysUserEntity> page = new Query<SysUserEntity>(params).getPage();
        List<SysUserEntity> userList = baseMapper.selectListPage1(page, params);
        
        for (SysUserEntity sysUserEntity : userList) {
        		//添加角色--用于显示人员角色
        	 List<SysRoleEntity> roleList = sysRoleService.queryRoleList(sysUserEntity.getUserId());
        		sysUserEntity.setRoleList(roleList);
        		//查询此人所在机构--用于显示此人所在机构名称--资质人员（专家）会在多加机构任职
             List<SysOrgEntity> orgList = sysOrgService.queryOrgList(sysUserEntity.getUserId());
             if (orgList != null && orgList.size() > 0) {
                for (SysOrgEntity sysOrgEntity : orgList) {
                    String orgTypeName = "";
                    Map<String, Object> dictParams = new HashMap<String, Object>();
                    if (sysOrgEntity != null && sysOrgEntity.getOrgType() != null && !"".equals(sysOrgEntity.getOrgType())) {
                        dictParams.put("value", sysOrgEntity.getOrgType());
                        dictParams.put("groupId", "ENT_TYPE");
                        if (sysDictService.queryByValueAndGroupId(dictParams) != null) {
                            orgTypeName = sysDictService.queryByValueAndGroupId(dictParams).getName();
                            sysOrgEntity.setOrgTypeName(orgTypeName);
                        } else {
                            sysOrgEntity.setOrgTypeName("");
                        }
                    }
                }
            }
            sysUserEntity.setOrgList(orgList);
        }
        return page.setRecords(userList);
    }

    @Override
    public List<String> queryAllMenuId(String userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public SysUserEntity queryByUserName(String userName) {
        SysUserEntity user = this.getOne(new QueryWrapper<SysUserEntity>().eq("USER_NAME", userName));
        String userId = "";
        if (user != null) {
            userId = user.getUserId();
            List<String> roleIdList = sysUserRoleService.queryRoleIdList(userId);
            user.setRoleIdList(roleIdList);
        }

        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysUserEntity user, Map<String, Object> params) {

        String password = user.getPassword();
        if (password == null || !"".equals(password)) {
            password = Constant.DEFAULT_PW;
        }
        user.setCreateTime(new Date());
        // sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(password, salt).toHex());
        user.setSalt(salt);
        this.save(user);
        ImUtils.users(user.getUserName(), Constant.DEFAULT_PW, user.getRealName());
            // 检查角色是否越权
            // checkRole(user, params);
            //保存用户与角色关系
            sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
            //保存用户与单位关系
            sysOrgUserService.updateOrgUser(user.getUserId(), user.getOrgNoList());
    }

    /**
     * 企业账号添加业务人员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(SysUserEntity user, Map<String, Object> params) {
    	Date createTime = new Date();
        user.setCreateTime(createTime);
        // sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
       
        String password = user.getPassword();
        if (password == null || !"".equals(password)) {
            password = Constant.DEFAULT_PW;
        }
        user.setPassword(new Sha256Hash(password, salt).toHex());
        user.setSalt(salt);
        this.save(user);
        ImUtils.users(user.getUserName(), Constant.DEFAULT_PW, user.getRealName());
        /*暂不使用  保存企业人员
        if (user != null) {
            SysOrgUserEntity orgUser = new SysOrgUserEntity();
            orgUser.setUserId(user.getUserId());
            orgUser.setUserCard(user.getUserCard());
            orgUser.setSeal(user.getSeal());
            orgUser.setOrgNo(user.getOrgNo());
            orgUser.setEmployStatus(UserEnum.employStatus.TYBPY.getKey());
            orgUser.setCreateTime(createTime);
            sysOrgUserService.add(orgUser, params);
        }*/
        // 保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    /**
     * 资质人员注册
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String registerUser(SysUserEntity user) {

    	String localip = "localhost";
        try {
        	 InetAddress ia=null;
			     ia=ia.getLocalHost();
	            localip=ia.getHostAddress();
	            System.out.println("获取IP地址"+localip);
		} catch (Exception e) {
			// TODO: handle exception
		}
    	
        user.setCreateTime(new Date());
        // sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        user.setStatus(AptitudeEnum.aptitudeStatus.WBS.getKey());
        user.setAccountType(SystemEnum.accountType.EXPERT.getKey());
        if(StringUtils.isNotBlank(user.getUserId())){
        	this.updateById(user);
        }else{
        	this.save(user);
            ImUtils.users(user.getUserName(), Constant.DEFAULT_PW, user.getRealName());
        }
        String userId = "";
        if (user != null && user.getUserId() != null) {
        	userId = user.getUserId();
            String userName = user.getUserName();  //登录名
            String email = user.getEmail();        //用户邮箱
            List<String> roleIdList = new ArrayList<String>();
            Map<String, Object> roleParams = new HashMap<>(2);
            //roleParams.put("roleCode", SystemEnum.roleType.ZZRY.getKey());
            List<String> roleList = sysRoleService.queryRoleIdList(roleParams);
            if (roleList != null && roleList.size() > 0) {
                for (String roleId : roleList) {
                    roleIdList.add(roleId);
                }
            }
            sysUserRoleService.saveOrUpdate(user.getUserId(), roleIdList);
            //生成验证标记
            String sign = "";
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            if (uuid != null && !"".equals(uuid)) {
                uuid = uuid.substring(0, 3);
                sign = userName + "_" + uuid;
            }
            //发送邮箱
            String mailHtml = Constant.EMAIL_HTML_REG;
            mailHtml = mailHtml.replaceAll("\\{emailTile\\}", emailTile);
            String webUrl = HttpContextUtils.getDomain();
            System.err.println(webUrl);
            mailHtml=mailHtml.replaceAll("\\{webUrl\\}", "http://"+localip+":70"); 
            System.err.println("emailParameter===" + emailParameter);
            mailHtml = mailHtml.replaceAll("\\{emailParameter\\}", emailParameter);

            String deSign = EncryUtils.encryption(sign); //翻译成密文
            mailHtml = mailHtml.replaceAll("\\{sign\\}", deSign);
            mailService.sendMail(email, "系统用户注册验证邮件", mailHtml);
        }
        return userId;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserEntity user, Map<String, Object> params) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            String salt = RandomStringUtils.randomAlphanumeric(20);
            user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        }
        this.updateById(user);
        // 检查角色是否越权
//		checkRole(user, params);
        // 保存用户与角色关系
        //判断需不需要更新人员与角色以及单位的关系
        String noUpdate = (String)params.get("noUpdate");
        if(StringUtils.isBlank(noUpdate)){
        	  sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
              sysOrgUserService.updateOrgUser(user.getUserId(), user.getOrgNoList());
        }
      
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String[] userIds) {
        this.removeByIds(Arrays.asList(userIds));
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsers(String[] userIds,String orgNo) {
    	//删除人员与企业的关系表数据
    	List<String> orgUserIdList = new ArrayList<String>();
        for(String userId:userIds){
       	 Map<String, Object> params = new HashMap<String, Object>();
   		 params.put("userId", userId);
   		 params.put("orgNo", orgNo);
   		 List<SysOrgUserEntity> orgUserList = sysOrgUserService.queryAll(params);
   		 for(SysOrgUserEntity sysOrgUserEntity:orgUserList){
   			 orgUserIdList.add(sysOrgUserEntity.getId());
   		 }
        }
        String[] orgUserIds = (String[]) orgUserIdList.toArray(new String[0]);
        sysOrgUserService.deleteBatch(orgUserIds);
        this.removeByIds(Arrays.asList(userIds));
    }

    @Override
    public boolean updatePassword(String userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void resetPws(String[] userIds) {
		for (int i = 0; i < userIds.length; i++) {
			SysUserEntity user = this.getById(userIds[i]);
			String salt = RandomStringUtils.randomAlphanumeric(20);
			user.setPassword(new Sha256Hash(Constant.DEFAULT_PW, user.getSalt()).toHex());
			this.updateById(user);
		}
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void resetPw(String userId) {
			SysUserEntity user = this.getById(userId);
			String salt = RandomStringUtils.randomAlphanumeric(20);
			user.setPassword(new Sha256Hash(Constant.DEFAULT_PW, user.getSalt()).toHex());
			this.updateById(user);
	}

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPw(String[] userIds) {
        for (int i = 0; i < userIds.length; i++) {
            SysUserEntity user = this.getById(userIds[i]);
            String salt = RandomStringUtils.randomAlphanumeric(20);
            user.setPassword(new Sha256Hash(Constant.DEFAULT_PW, salt).toHex());
            this.updateById(user);
        }
    }


    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user, Map<String, Object> params) {
        if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
            return;
        }

        // 查询用户权限下的角色列表
        List<String> roleIdList = sysRoleService.queryRoleIdList(params);

        // 判断是否越权
        if (!roleIdList.containsAll(user.getRoleIdList())) {
            throw new BusinessException("新增用户所选角色，不是本人创建");
        }
    }

    @Override
    public String getAdminUserIdByOrg(String orgNo) {
        return baseMapper.getAdminUserIdByOrg(orgNo);
    }
    
    /**
     * @Auther:wangLc 
     * @Date: 2019-7-16 10:08
     * @Description: 根据菜单表的 PERMS（授权）查询相应人员
     */
    @Override
    public List<SysUserEntity> selectFlowUser(String orgNo,String perms){
    	Map<String, Object> params = new HashMap<String, Object>();
	    	params.put("orgNo", orgNo);
	    	params.put("perms", perms);
    	return baseMapper.selectFlowUser(params);
    }

}
